<template>
  <div class="form-fragment">
    <div class="form-container">
      <tbc-dynamic-form :form="dynamicForm" ref="form" class="compact">
        <template v-slot:region="scope">
          <tbc-selector api="/basic.region" v-model="scope.item.value" level="3" style="width: 100%"/>
        </template>
      </tbc-dynamic-form>
    </div>
  </div>
</template>
<script lang="ts">
import {defineComponent, reactive} from 'vue'

export default defineComponent({

  name: 'goods-form-shipping',

  setup() {

    const dynamicForm = reactive([
      {label: '商品重量', type: 'input-number', field: 'weight', value: 0},
      {label: '商品体积', type: 'input-number', field: 'volume', value: 0},
      {label: '商品发货地', type: 'custom', field: 'region', value: []},
    ])

    const init = (data: Record<string, string>): void => {
      initDynamicFormData(data)
    }

    const initDynamicFormData = (data: Record<string, string>): void => {
      dynamicForm.forEach((item: { [k: string]: string | string[] | number }) => {
        const field: string = item.field as string
        if (item.field === 'region') {
          (item.value as string[]) = [data.province, data.city, data.district]
        } else {
          if (typeof data[field] !== 'undefined') item.value = Number(data[field])
        }
      })
    }

    const getFormData = (): Record<string, number | string> => {
      let form: Record<string, string | number> = {}
      dynamicForm.forEach((item: { [k: string]: string | number | string[] }) => {
        if (item.field === 'region') {
          let region = JSON.parse(JSON.stringify(item.value))
          form.province = region.length ? region.shift() : ''
          form.city = region.length ? region.shift() : ''
          form.district = region.length ? region.shift() : ''
        } else {
          form[(item.field as string)] = item.value as string | number
        }
      })
      return form
    }

    return {
      dynamicForm,
      init,
      getFormData
    }
  }
})
</script>